﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AugustaDevelopersGuild.Models;

namespace AugustaDevelopersGuild.Controllers
{
    public class RsvpController : Controller
    {
        IMeetingRepository meetingRepository;

        public RsvpController()
            : this(new MeetingRepository()) {
        }

        public RsvpController(IMeetingRepository repository)
        {
            meetingRepository = repository;
        }

        [Authorize, HttpPost]
        public ActionResult Register(int id)
        {
            Meeting meeting = meetingRepository.Find(id);

            if (!meeting.IsUserRegistered(User.Identity.Name))
            {
                Rsvp rsvp = new Rsvp();
                rsvp.AttendeeNameId = User.Identity.Name;
                rsvp.AttendeeName = User.Identity.Name;
                rsvp.MeetingID = meeting.MeetingID;

                GuildMeetings meetings = new GuildMeetings();
                meetings.Rsvps.Add(rsvp);
                meetings.SaveChanges();
            }

            return Content("Thanks - we'll see you there!");
        }

        //
        // AJAX: /RSVP/Cancel/1

        [Authorize, HttpPost]
        public ActionResult Cancel(int id)
        {
            Meeting meeting = meetingRepository.Find(id);

            Rsvp rsvp = meeting.Rsvps
                .Where(r => User.Identity.Name == (r.AttendeeNameId ?? r.AttendeeName))
                .SingleOrDefault();

            if (rsvp != null)
            {
                meetingRepository.DeleteRsvp(rsvp);
                meetingRepository.Save();
            }

            return Content("Sorry you can't make it!");
        }
    }
}
